﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinanceGoldPointDal.DTO.Trans;
using MaasOne.Finance.YahooFinance;
using FinanceGoldPointDal.DAL;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace FinanceGoldPointDal.Utils
{
  public class MaasGetDatiSimbolo : baseDAL
  {
 


   //MAASONE
    public void getdatiSimbolo(string pSimbolo)
    {
      //Profilo Compagnia
      //var res = new MaasOne.Finance.YahooFinance.CompanyProfileDownload().Download(new CompanyProfileDownloadSettings(pSimbolo));

      ////Statistiche chiave > trading info
      //var res1 = new MaasOne.Finance.YahooFinance.CompanyStatisticsDownload().Download(pSimbolo);
      //var keyinfo = res1.Result.Item.TradingInfo;

      var res12 = new MaasOne.Finance.YahooFinance.QuotesDownload().Download(pSimbolo,
        new[] { QuoteProperty.Symbol, QuoteProperty.Open, QuoteProperty.DaysHigh, QuoteProperty.DaysLow });

      var res5 = new MaasOne.Finance.YahooFinance.MarketDownload().DownloadAllSectors();

      var rr = new MaasOne.Finance.YahooFinance.QuoteOptionsDownload().Download();

      var tt = new MaasOne.Finance.YahooFinance.MarketQuotesDownload().Download( );

      var res2 = new MaasOne.Finance.YahooFinance.HistQuotesDownload().Download(pSimbolo, DateTime.Now.AddDays(-10), DateTime.Now, HistQuotesInterval.Daily);

      var res3 = new MaasOne.Finance.YahooFinance.MarketQuotesDownload().DownloadAllSectorQuotes();

      var res4 = new MaasOne.Finance.YahooFinance.MarketDownload().Download();

     

    }//fM


    /// <summary>
    /// verifica se ci sono buone azioni in rilievo da comprare
    /// </summary>
    public void controllaSimboliBuoni()
    {

     // getdatiSimbolo("ACP.MI");

      using (var dal = getNewDAL())
      {
        dal.Simboli.MergeOption = System.Data.Objects.MergeOption.NoTracking;


        //prelevo i simboli
        var simboliDb = dal.Simboli.ToList();
        double tot = dal.Simboli.Count();
        double div = tot / 3;

        var totStat = dal.StatChiaveSimboli.Count();
        if (totStat > 0)
        {
          var datas = dal.StatChiaveSimboli.Max(xx => xx.Data);
          if (datas.Date == DateTime.Now.Date)
            dal.ExecuteStoreCommand(string.Format("delete from StatChiaveSimboli where data = '{0}'", DateTime.Now.ToString("yy-mm-dd")));

          //dal.ExecuteStoreCommand("Truncate table StatChiaveSimboli");
        }      
       

        var list1 = simboliDb.Take((int)div).ToList();
        var list2 = simboliDb.Skip((int)div).Take((int)div).ToList();
        var list3 = simboliDb.Skip((int)div * 2).Take((int)div + 2).ToList();  
        
        Task<System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> >[] tasks = new Task<ConcurrentBag<StatChiaveSimboli>>[3];

        tasks[0]  = Task<System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> >.Factory.StartNew(()=> getSimboliBuoni( list1 )   );
        tasks[1] = Task<System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> >.Factory.StartNew(()=> getSimboliBuoni( list2 )   );
        tasks[2] = Task<System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> >.Factory.StartNew(()=> getSimboliBuoni( list3 )   );

        
        //salva
        foreach (var item in tasks)
        {
          foreach (var simb in item.Result)
	        {
		        try
                  {
                    dal.AddToStatChiaveSimboli(simb);
                    dal.SaveChanges();
                  }
                  catch (Exception)
                  { } 
	        }
          
        }


      }     


    }//fM

    public System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> getSimboliBuoni(IList<Simboli> pItems)
    {

      // getdatiSimbolo("ACP.MI");

      double open = 0, high = 0, low = 0;
      MaasOne.Base.Response<MaasOne.Finance.YahooFinance.CompanyStatisticsResult> result = null;
      MaasOne.Base.Response<MaasOne.Finance.YahooFinance.QuotesResult> result2 = null;
      MaasOne.Finance.YahooFinance.CompanyTradingInfo tradInfoRes = null;
      //StatChiaveSimboli dato = null;

      var getter = new MaasOne.Finance.YahooFinance.CompanyStatisticsDownload();//esegue il download
      var getter2 = new MaasOne.Finance.YahooFinance.QuotesDownload();

      System.Collections.Concurrent.ConcurrentBag<StatChiaveSimboli> bag = new ConcurrentBag<StatChiaveSimboli>();


        foreach (var item in pItems)
        {
          result = getter.Download(item.Code);
          result2 = getter2.Download(item.Code,
            new[] { QuoteProperty.Symbol, QuoteProperty.Open, QuoteProperty.DaysHigh, QuoteProperty.DaysLow });

          if (result.Result.Item != null)
          {
            tradInfoRes = result.Result.Item.TradingInfo;

            if (tradInfoRes.AverageVolumeTenDaysInThousand > tradInfoRes.AverageVolumeThreeMonthInThousand)
            {
              var dato = StatChiaveSimboli.CreateStatChiaveSimboli(item.Code, DateTime.Now, item.Isin);
              dato.Isin = item.Isin;
              dato.Location = item.Location;

              try
              {
                if (double.TryParse(result2.Result.Items[0].Open.ToString(), out open))
                  dato.PriceDayOpen = open;

                if (double.TryParse(result2.Result.Items[0].DaysHigh.ToString(), out high))
                  dato.PriceDayHigh = high;

                if (double.TryParse(result2.Result.Items[0].DaysLow.ToString(), out low))
                  dato.PriceDayLow = low;
              }
              catch { }

              dato.TrendVolumiPositivo = true;
              dato.TrendVolumiPerc = Math.Round(tradInfoRes.AverageVolumeTenDaysInThousand / tradInfoRes.AverageVolumeThreeMonthInThousand, 1);
              dato.Volumi10gg = tradInfoRes.AverageVolumeTenDaysInThousand;
              dato.VolumiTreMesi = tradInfoRes.AverageVolumeThreeMonthInThousand;
              dato.ROE = result.Result.Item.FinancialHighlights.ReturnOnEquityPercent;
              dato.ROA = result.Result.Item.FinancialHighlights.ReturnOnAssetsPercent;

              dato.MargineProfitto = result.Result.Item.FinancialHighlights.ProfitMarginPercent;
              dato.MargineOperativo = result.Result.Item.FinancialHighlights.OperatingMarginPercent;

              dato.CrescitaRicaviTrim = result.Result.Item.FinancialHighlights.QuarterlyRevenueGrowthPercent;//ricavi
              dato.CrescitaUtiliTrim = result.Result.Item.FinancialHighlights.QuaterlyEarningsGrowthPercent;//utili

              dato.MediaMob50gg = tradInfoRes.FiftyDayMovingAverage;
              dato.MediaMob200gg = tradInfoRes.TwoHundredDayMovingAverage;

              dato.PriceMaxOneYear = tradInfoRes.OneYearHigh;
              dato.PriceMinOneYear = tradInfoRes.OneYearLow;
              dato.VarPercOneYear = tradInfoRes.OneYearChangePercent;

              //dato.PunteggioVal 

              // dato.Data = DateTime.Now;

              bag.Add(dato);
            }
          }

        };//fine parallel


        return bag;

      
    }//fM



  }//fC

}
